package com.yanze.schoolinformation.viewModule.person;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;

import com.yanze.schoolinformation.R;
import com.yanze.schoolinformation.app.C;
import com.yanze.schoolinformation.model.bean.resp.RespUser;
import com.yanze.schoolinformation.model.http.DeforObserver;
import com.yanze.schoolinformation.model.http.reqo.DataReqo;
import com.yanze.schoolinformation.utils.FilePathManager;
import com.yanze.schoolinformation.utils.SPUtils;
import com.yanze.schoolinformation.utils.ToastUtils;
import com.yanze.schoolinformation.utils.ToolUtils;
import com.yanze.schoolinformation.view.my.person.PersonActivity;

import java.io.File;
import java.io.IOException;

import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * Created by MrZheng on 2018/5/8.
 */

public class PersonViewModel {
    PersonActivity mActivity;
    PersonNavigator mNavigator;

    private File cameraFile;//拍照后的照片文件

    public static final int REQUEST_CROP = 100;
    public static final int RESULT_CROP = 101;
    public static final int REQUEST_LOCAL = 111;
    public static final int REQUEST_CAMERA = 112;

    public PersonViewModel(PersonActivity mActivity) {
        this.mActivity = mActivity;
    }

    public void setmNavigator(PersonNavigator mNavigator) {
        this.mNavigator = mNavigator;
    }

    //检查权限 动态申请授权
    public void checkPermissionForNormal(String permission) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            if (permission.equals(Manifest.permission.CAMERA)) {
                cameraImage();
            } else if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                localImage();
            }
            return;
        }
        //判断是否授权拍照  Manifest.permission.CAMERA
        if (ContextCompat.checkSelfPermission(mActivity, permission) != PackageManager.PERMISSION_GRANTED) {
            //如果之前申请,并且用户点击了拒绝,会返回true
            String msg = "";
            int code = 1;
            if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                msg = mActivity.getString(R.string.NOAUTHORIZATION_NO_ALBUM);
                code = 101;
            } else if (permission.equals(Manifest.permission.CAMERA)) {
                msg = mActivity.getString(R.string.NOAUTHORIZATION_NO_CAMERA);
                code = 100;
            }
            if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.CAMERA)) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
                dialog.setMessage(msg);
                dialog.setPositiveButton(mActivity.getString(R.string.to_setting), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent()
                                .setAction("android.settings.APPLICATION_DETAILS_SETTINGS")
                                .setData(Uri.fromParts("package",
                                        mActivity.getPackageName(), null));
                        mActivity.startActivity(intent);
                    }
                });
                dialog.show();
            } else {
                //去申请权限
                ActivityCompat.requestPermissions(mActivity, new String[]{permission}, code);
            }
        } else {
            if (permission.equals(Manifest.permission.CAMERA)) {
                cameraImage();
            } else if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                localImage();
            }
        }
    }

    //授权回调
    public void requestPermissionResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        cameraImage();
                    }
                } else {
                    ToastUtils.show(mActivity, mActivity.getString(R.string.NOAUTHORIZATION_CAMERA));
                }
                break;
            case 101:
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        localImage();
                    }
                } else {
                    ToastUtils.show(mActivity, mActivity.getString(R.string.NOAUTHORIZATION_ALBUM));
                }
                break;
        }
    }

    /**
     * 拍照
     */
    private void cameraImage() {
        cameraFile = FilePathManager.getCameraCache(mActivity);
        if (cameraFile.exists()) {
            cameraFile.delete();
        }
        try {
            cameraFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri cameraUri = ToolUtils.getFileUri(mActivity, cameraFile);
        Intent intent3 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent3.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        mActivity.startActivityForResult(intent3, REQUEST_CAMERA);
    }

    /**
     * 从相册获取图片
     */
    private void localImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        mActivity.startActivityForResult(intent, REQUEST_LOCAL);
    }

    public void UpLoadHeader() {
        //获取剪裁之后的图片回调
        String userId = (String) SPUtils.get(mActivity, "userid", "");
        if (userId.equals("")) {
            ToastUtils.show(mActivity, "用户数据错误，请重新登录");
            return;
        }
        final File file = FilePathManager.getCropdFilePath(mActivity);
        MediaType IMAGE_TYPE = MediaType.parse("image/jpeg");
        RequestBody requestBody = RequestBody.create(IMAGE_TYPE, file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        DataReqo.getInstant().upHeader(C.url.API_School, userId, body)
                .subscribe(new DeforObserver<RespUser>() {
                    @Override
                    public void _onSubscribe(Disposable disposable) {
                        mActivity.addSubscription(disposable);
                    }

                    @Override
                    public void _onNext(RespUser entity) {
                        if (entity.getStatus() == 200) {
                            mNavigator.uploadSuccess(entity);
                            mNavigator.showImage(entity.getData().getUsericon());
                        } else {
                            mNavigator.uploadFail(entity.getMsg());
                        }
                    }

                    @Override
                    public void _onError(String msg) {
                        mNavigator.uploadFail(msg);
                    }
                });
    }

    public void onDestory() {
        mActivity = null;
        mNavigator = null;
    }
}
